package com.lx.sync.consumer.sync;

import com.lx.sync.api.dto.PageResult;
import com.lx.sync.api.dto.SyncDataDTO;
import com.lx.sync.api.feign.DataSyncFeignClient;
import com.lx.sync.common.util.CacheUtil;
import com.lx.sync.consumer.entity.SyncData;
import com.lx.sync.consumer.service.SyncDataService;
import com.lx.sync.core.executor.AbstractSyncService;
import com.lx.sync.core.model.SyncFetchDataRequest;
import com.lx.sync.core.model.SyncPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SyncDemoService
 * @Description: //todo
 * @Author: 落雪
 * @CreateDate: 2025/5/13 22:00
 * @UpdateUser: 落雪
 * @UpdateDate: 2025/5/13 22:00
 * @UpdateRemark:
 * @Version: 1.0
 */
@Slf4j
@Component
public class SyncDemoService extends AbstractSyncService<SyncData> {



    @Autowired
    private DataSyncFeignClient dataSyncFeignClient;

    @Autowired
    private SyncDataService syncDataService;

    @Autowired
    public SyncDemoService(CacheUtil cacheUtil) {
        super(cacheUtil);
    }

    @Override
    protected String getIdxName() {
        return "demo";
    }

    @Override
    protected SyncPage fetchSourceData(SyncFetchDataRequest request) {

        try {
            SyncDataDTO syncDataDTO = new SyncDataDTO();
            syncDataDTO.setUpdateTime(request.getUpdtTime());
            syncDataDTO.setPageNum(request.getPageNum());
            syncDataDTO.setPageSize(request.getPageSize());
            syncDataDTO.setQueryCount(request.getQueryCount());
            syncDataDTO.setLastId(request.getLastId());
            syncDataDTO.setPageMode(request.getPageMode());
            PageResult<SyncDataDTO> page = dataSyncFeignClient.getSyncData(syncDataDTO);
            List<SyncData> convert = page.getRecords().stream().map(item -> convertToDo(item)).collect(Collectors.toList());
            //转换为 SyncPage
            SyncPage<SyncData> syncPage = new SyncPage<>();
            syncPage.setRecords(convert);
            if(request.getPageMode() ==2){
                syncPage.setPageSize(request.getPageSize());
                syncPage.setPageNumber(request.getPageNum());
                syncPage.setTotalPages((int) page.getPages());
                syncPage.setRecordCount((int) page.getTotal());
            }

            return syncPage;
        } catch (Exception e) {

            log.error("同步数据出错", e);
        }


        return null;
    }

    private SyncData convertToDo(SyncDataDTO syncDataDTO) {
        SyncData syncData = new SyncData();
        BeanUtils.copyProperties(syncDataDTO, syncData);
        return syncData;
    }

    @Override
    protected void bulkToDb(List<SyncData> syncDataList) {
        syncDataService.saveBatch(syncDataList);

    }
}
